package business

import (
	"fcs-api/src/app/model"
	"fcs-api/src/app/service/route"
	k8s "fcs-api/src/client/kubernetes"
)

func CreateAlias(fcClient *k8s.FcClient, alias *model.FuncAlias) (*model.FuncAlias, error) {
	_, err := route.CreateRoute(fcClient, alias)
	if err != nil {
		_ = logger.Error("CreateAlias: create route error, %v", err)
		return nil, err
	}
	_, err = model.CreateAlias(alias)
	if err != nil {
		_ = logger.Error("CreateAlias: insert alias db error, %v", err)
		return nil, err
	}
	return alias, nil
}

func UpdateAlias(fcClient *k8s.FcClient, alias *model.FuncAlias) (*model.FuncAlias, error) {
	_, err := route.UpdateRoute(fcClient, alias)
	if err != nil {
		_ = logger.Error("UpdateAlias: create route error, %v", err)
		return nil, err
	}
	_, err = model.UpdateAlias(alias)
	if err != nil {
		_ = logger.Error("UpdateAlias: insert alias db error, %v", err)
		return nil, err
	}
	return alias, nil
}

func GetAliasList(functionId string) ([]*model.FuncAlias, error) {
	aliasList, err := model.GetAliasList(functionId)
	if err != nil {
		_ = logger.Error("GetAliasList: get list from db error, %s", err.Error())
		return nil, err
	}
	return aliasList, nil
}

func DeleteAlias(fcClient *k8s.FcClient, alias *model.FuncAlias) error {
	err := route.DeleteRoute(fcClient, alias)
	if err != nil {
		_ = logger.Error("DeleteAlias: delete route error %s", err.Error())
		return err
	}
	err = model.DeleteAlias(alias.FuncId, alias.AliasName)
	if err != nil {
		_ = logger.Error("DeleteAlias: delete alias database error %s", err.Error())
		return err
	}
	return nil
}
